package com.cloud.form.api.translator;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.Document;
import com.cloud.form.api.entity.FormAssemblyInst;

public class CheckboxTranslator {
	private static final Logger logger = LoggerFactory.getLogger(CheckboxTranslator.class);

	public static void translator(Document doc, String bookmark, String value, FormAssemblyInst inst) {
		BookmarkCollection bookMarks = doc.getRange().getBookmarks();
		@SuppressWarnings("unchecked")
		Iterator<Bookmark> it = bookMarks.iterator();
		List<Object> valueList = Arrays.asList(JSON.parseArray(value).toArray());
		while (it.hasNext()) {
			Bookmark mark = it.next();
			if (mark.getName().equals(bookmark)) {
				JSONArray itemArray = JSONObject.parseObject(inst.getConfigAttributes()).getJSONArray("items");
				StringBuilder labelValue = new StringBuilder("");
				@SuppressWarnings("rawtypes")
				Iterator itemIterator = itemArray.iterator();
				while (itemIterator.hasNext()) {
					JSONObject obj = (JSONObject) itemIterator.next();
					String label = obj.getString("label");
					if (valueList.contains(obj.getString("value"))) {
						labelValue.append("☑");
					} else {
						labelValue.append("□");
					}
					labelValue.append(label).append(" ");
				}
				try {
					mark.setText(labelValue.toString());
				} catch (Exception e) {
					logger.error("字符替换失败", e);
				}
			}
		}
	}

}
